package ytdp.careagle.com.ytdp.myview;

import android.content.Context;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

/**
 * Created by admin on 2017/9/27.
 */

public class MyEditText extends EditText {

    private ClickListener listener;
    private float textOneWidth;

    public MyEditText(Context context) {
        this(context, null);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        TextPaint mTextPaint = getPaint();
        textOneWidth = mTextPaint.measureText("1");
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                float x = event.getX();
                int paddingLeft = getPaddingLeft();
                float v = (x - paddingLeft) / textOneWidth;
                if (v >= getText().toString().length()) {
                    v = getText().length();
                } else if (v < 0) {
                    v = 0;
                }
                setSelection((int) v);
                if (listener != null) {
                    listener.onClick(this);
                }
                break;
        }

        return true;
    }

    public void setListener(ClickListener listener) {
        this.listener = listener;
    }

    public interface ClickListener {
        void onClick(View view);
    }
}
